package com.itheima.reggie.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author Serendipity
 * @version 1.0
 * @date 12/25/21 6:05 PM
 */
@RestController
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/dish/list")
    public ResultInfo findByCategoryId(
            Long categoryId,
            @RequestParam(defaultValue = "1")  Integer status,
            String name){
//        调用查询
        String key = "dish_" + categoryId;//保存到redis中的键
        List<Dish> dishList = (List<Dish>) redisTemplate.opsForValue().get(key);
        if (CollectionUtil.isNotEmpty(dishList)) {
            //如果存在，直接返回
            return ResultInfo.success(dishList);
        }else {
            //如果不存在
            dishList =dishService.findList(categoryId, status, name);
            //将结果保存到redis
            redisTemplate.opsForValue().set(key, dishList);
            //返回
            return ResultInfo.success(dishList);
        }
    }
}
